package com.businessportal.web.controllers.admin;

import com.businessportal.web.dataaccess.entities.Login;
import com.businessportal.web.dataaccess.services.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Vadim on 1/15/2015.
 */

@WebServlet(urlPatterns = "/securepages/address_creator.do")
public class AddressCreatorController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try
        {
            req.setCharacterEncoding("UTF-8");

            HttpSession session = req.getSession();
            Login user = (Login) session.getAttribute("user");


            req.setAttribute("title", "Create Address");
            //req.setAttribute("country", user.getRole());

        }
        catch (Exception e)
        {

        }

        getServletContext().getRequestDispatcher("/securepages/address_creator.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try
        {
            req.setCharacterEncoding("UTF-8");

            HttpSession session = req.getSession();
            Login user = (Login) session.getAttribute("user");

            if(null != user) {
                String country = req.getParameter("country");
                String city = req.getParameter("city");
                String street = req.getParameter("street");
                String postal = req.getParameter("postal");

                UserService.INSTANCE.AddAddress(user, postal, country, city, street);

                resp.sendRedirect("/securepages/admin_portal.jsp");

                return;
            } else {
                throw new Exception("Couldn't get authorization information");
            }
        }
        catch(Exception e)
        {
            req.setAttribute("Error", e.getMessage());
        }

        getServletContext().getRequestDispatcher("/securepages/address_creator.jsp").forward(req, resp);
    }
}
